﻿<%@ WebHandler Language="C#" Class="WorkReportSearch" %>

using System;
using System.Web;
using Chenxin.Lib.Utility;
using System.Data;
using System.Text;
using System.Data.SqlClient;

public class WorkReportSearch : AjaxHandlerBase 
{
    
    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";

        if (!string.IsNullOrEmpty(context.Request.Params["op"]))
        {
            //处理类型
            string strOperate = context.Request.Params["op"];

            switch (strOperate.Trim())
            {
                case "search":
                    SearchWorkReport(context);
                    break;
                case "dellist":
                    DelWorkReport(context);
                    break;
                case "restorelist":
                    RestoreWorkReport(context);
                    break;
                case "setisread":
                    SetWorkReportIsRead(context);
                    break;
                default:
                    break;
            }
        }
    }

    public void SearchWorkReport(HttpContext context)
    {
        try
        {
            //查询条件
            StringBuilder sb = new StringBuilder();
            sb.Append(" (1=1) ");

            //所要查询的表名
            string strTableName = "WorkReport_InBox as i, WorkReport_OutBox as o left join Attachment as a on o.RecordId = a.RelationId ";
            //排序
            string strOrderField = "o.SendTime desc";
            //checkbox(name)
            string strckname = "unreadedck";
            string strdelID = "InRecordId";
            //子查询欲选择字段列表
            string TableFieldList = "o.RecordId as OutRecordId, o.SenderId, o.SenderName, o.SenderCode, o.SendTime, o.Subject, o.Content, o.SenderDepartId, o.SenderDepartName, o.SenderCompanyId, o.SenderCompanyName, o.SenderCityId, o.SenderCityName, o.ReceiverId as OutReceiverId, o.ReceiverName as OutReceiverName , i.RecordId as InRecordId, i.WorkReportId, i.ReceiverId as InReceiverId, i.ReceiverName as InReceiverName, i.ReceiverDepartId, i.ReceiverDepartName, i.ReceiverCompanyId, i.ReceiverCompanyName, i.ReceiverCityId, i.ReceiverCityName, i.isReaded, a.[Path], a.[Type], a.FileName";
            //查看类别
            string strType = context.Request.Params["type"];

            switch (strType.Trim())
            {
                case "unreaded"://未读
                    sb.AppendFormat(" and o.RecordId = i.WorkReportId and i.isReaded = 'false' and i.isDeleted = 'false' and i.ReceiverId ='{0}'", CurrentUserInfo.UserId);
                    strckname = "unreadedck";
                    GetDBWhere(context, sb, strType);
                    break;
                case "isreaded"://已读
                    sb.AppendFormat(" and o.RecordId = i.WorkReportId and i.isReaded = 'true' and i.isDeleted = 'false' and i.ReceiverId ='{0}'", CurrentUserInfo.UserId);
                    strckname = "isreadedck";
                    GetDBWhere(context, sb, strType);
                    break;
                case "outbox"://发件箱
                    strTableName = "WorkReport_OutBox as o left join Attachment as a on o.RecordId = a.RelationId ";
                    sb.AppendFormat(" and o.isDeleted = 'false' and o.SenderId ='{0}'", CurrentUserInfo.UserId);
                    strckname = "outboxck";
                    strdelID = "OutRecordId";
                    TableFieldList = "o.RecordId as OutRecordId, o.SenderId, o.SenderName, o.SenderCode, o.SendTime, o.Subject, o.Content, o.SenderDepartId, o.SenderDepartName, o.SenderCompanyId, o.SenderCompanyName, o.SenderCityId, o.SenderCityName, o.ReceiverId as OutReceiverId, o.ReceiverName as OutReceiverName, a.[Path], a.[Type], a.FileName";
                    GetDBWhere(context, sb, strType);
                    break;
                case "dustbin"://垃圾箱
                    sb.AppendFormat(" and o.RecordId = i.WorkReportId and i.isDeleted = 'true' and i.ReceiverId ='{0}'", CurrentUserInfo.UserId);
                    strckname = "dustbinck";
                    GetDBWhere(context, sb, strType); 
                    break;
                default:
                    sb.AppendFormat(" and o.RecordId = i.WorkReportId and i.isReaded = 'false' and i.isDeleted = 'false' and i.ReceiverId ='{0}'", CurrentUserInfo.UserId);
                    strckname = "unreadedck";
                    GetDBWhere(context, sb, strType);
                    break;
            }

            sb.Append("and (a.[Type] = 10 or a.[Type] is null)");
            
            int count = 0;
            Constants.Pagination stuPg = new Constants.Pagination();

            //页码
            int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            //页显示行数
            int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            //欲选择字段列表 
            string FieldList = "*";

            //根据sql执行查询
            DataSet ds = Chenxin.Lib.Hr.DAL.WorkReport_InBox.GetList(strPageSize, strPageIndex, strOrderField, strTableName, sb.ToString(), FieldList, TableFieldList, true);
            //数据量
            count = (int)ds.Tables[1].Rows[0][0];

            string strHtml = string.Empty;

            int counts = (strPageIndex - 1) * strPageSize;

            if (!GetWorkReportHtml(context, ds, counts, strckname, strdelID, out strHtml))
            {
                context.Response.Write(retExecResult(Constants.ExecResult.Error, "生成HTML错误", ""));
            }
            stuPg.count = count;
            stuPg.data = strHtml.ToString();

            context.Response.Write(retExecResult(Constants.ExecResult.Succ, "OK", stuPg));

        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    private void GetDBWhere(HttpContext context, StringBuilder sb, string strType)
    {
        if ("1".Equals(context.Request.Params["tag"]))
        {
            //发件箱
            if (strType == "outbox")
            {

                if (!string.IsNullOrEmpty(context.Request.Params["receivername"]))
                {
                    sb.AppendFormat("and (o.ReceiverName like '%{0}%')", context.Request.Params["receivername"].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(context.Request.Params["sendtime"]))
                {
                    sb.AppendFormat("and (Convert(varchar(10),o.SendTime,120) like '%{0}%')", context.Request.Params["sendtime"].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(context.Request.Params["subject"]))
                {
                    sb.AppendFormat("and (o.Subject like '%{0}%')", context.Request.Params["subject"].ToString().Trim());
                }

            }
            //未读，已读，垃圾箱
            else
            {

                if (!string.IsNullOrEmpty(context.Request.Params["sendername"]))
                {
                    sb.AppendFormat("and (o.SenderName like '%{0}%')", context.Request.Params["sendername"].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(context.Request.Params["sendtime"]))
                {
                    sb.AppendFormat("and (Convert(varchar(10),o.SendTime,120) like '%{0}%')", context.Request.Params["sendtime"].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(context.Request.Params["subject"]))
                {
                    sb.AppendFormat("and (o.Subject like '%{0}%')", context.Request.Params["subject"].ToString().Trim());
                }

            }

        }
    }

    private bool GetWorkReportHtml(HttpContext context, DataSet dslist, int counts, string ckname, string recordId, out string strHtml)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<table style=\"width:100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
        sb.Append("<thead>");
        sb.Append("<tr>");
        sb.Append("<th width=\"15px;\" style=\"text-align:center;\"><label id=\"lblck\" ><input id=\"ckdel\" type=\"checkbox\" title=\"全选/反选\"/></label></th>");
        sb.Append("<th width=\"15px;\">序号</th>");
        sb.Append("<th width=\"80px;\">发送人</th>");
        sb.Append("<th width=\"80px;\">发送时间</th>");
        sb.Append("<th width=\"150px;\">工作报告主题</th>");
        sb.Append("<th width=\"15px;\">详细</th>");
        sb.Append("<th width=\"15px;\">附件</th>");
        sb.Append("</tr>");
        sb.Append("</thead>");
        sb.Append("<tbody>");

        DataTable dt = dslist.Tables[0];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string strSendtime = Convert.ToDateTime(dt.Rows[i]["SendTime"].ToString()).ToString("yyyy-MM-dd");
            TimeSpan ts = Convert.ToDateTime(strSendtime).Subtract(Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")));
            string style = "";
            if (ts.Days == 0)
            {
                style = "color:red";       
            }
            sb.AppendFormat("<tr id=\"{0}\" >", dt.Rows[i]["" + recordId + ""].ToString());

            sb.AppendFormat("<td style=\"text-align:center;\"><input name=\"" + ckname + "\" type=\"checkbox\" value=\"{0}\"/></td>", dt.Rows[i]["" + recordId + ""].ToString());
            sb.AppendFormat("<td style=\"text-align:center; {0}\">{1}</td>", style, (i + 1 + counts).ToString());
            sb.AppendFormat("<td style=\"{0}\">{1}</td>", style, dt.Rows[i]["SenderName"].ToString());
            sb.AppendFormat("<td style=\"{0}\">{1:yyyy-mm-dd hh-mm-ss}</td>", style, dt.Rows[i]["SendTime"].ToString());
            sb.AppendFormat("<td style=\"{0}\">{1}</td>", style, dt.Rows[i]["Subject"].ToString());
            if ("outboxck".Equals(ckname))
                sb.AppendFormat("<td style=\"text-align:center;\"><a name=\"{0}\" id=\"btndetail\" href=\"WorkReportDetailInfo.aspx?RecordId={0}\" title=\"详情\">详</a></td>", dt.Rows[i]["" + recordId + ""].ToString());
            else
                sb.AppendFormat("<td style=\"text-align:center;\"><a name=\"{0}\" id=\"btndetail\" href=\"#\" title=\"详情\">详</a></td>", dt.Rows[i]["" + recordId + ""].ToString());

            if (System.IO.File.Exists(context.Server.MapPath(Constants.DIRECTORY + dt.Rows[i]["Path"].ToString())))
                //sb.AppendFormat("<td style=\"text-align:center;\"><a title=\"{0}\" id=\"abtnreply\" href=\"{1}\" target=\"_blank\">附</a></td>", dt.Rows[i]["FileName"].ToString(), Constants.DIRECTORY + dt.Rows[i]["Path"].ToString());
                sb.AppendFormat("<td style=\"text-align:center;\"><a title=\"{0}\" id=\"abtnreply\" href=\"/service/Download.ashx?file=/{1}\" target=\"_blank\">附</a></td>", dt.Rows[i]["FileName"].ToString(), dt.Rows[i]["Path"].ToString());
            else
                sb.Append("<td style=\"text-align:center;\" title=\"无附件\"><span> - </span></td>");

            sb.Append("</tr>");
        }

        sb.Append("</tbody></table>");

        strHtml = sb.ToString();
        return true;
    }

    public void DelWorkReport(HttpContext context)
    {
        try
        {
            if (string.IsNullOrEmpty(context.Request["modelid"]))
                context.Response.Write(retExecResult(Constants.ExecResult.Error, "标识不存在，请重试！", ""));

            string strRecordId = context.Request["modelid"];
            string[] idlist = strRecordId.Split(',');
            for (int i = 0; i < idlist.Length; i++)
            {
                string strType = context.Request.Params["type"];
                if (strType == "outbox")
                {
                    Chenxin.Lib.Hr.Entity.WorkReport_OutBox model = Chenxin.Lib.Hr.BLL.WorkReport_OutBox.GetModel(new Guid(idlist[i]));
                    model.isDeleted = true;
                    Chenxin.Lib.Hr.BLL.WorkReport_OutBox.Update(model);
                }
                else if (strType == "dustbin")
                {
                    Chenxin.Lib.Hr.BLL.WorkReport_InBox.Delete(new Guid(idlist[i]));
                }
                else
                {
                    Chenxin.Lib.Hr.Entity.WorkReport_InBox model = Chenxin.Lib.Hr.BLL.WorkReport_InBox.GetModel(new Guid(idlist[i]));
                    model.isDeleted = true;
                    model.isReaded = true;
                    Chenxin.Lib.Hr.BLL.WorkReport_InBox.Update(model);
                }
            }
            context.Response.Write(retExecResult(Constants.ExecResult.Succ, "删除成功！", ""));
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }  
    }

    public void RestoreWorkReport(HttpContext context)
    {
        try
        {
            if (string.IsNullOrEmpty(context.Request["modelid"]))
                context.Response.Write(retExecResult(Constants.ExecResult.Error, "标识不存在，请重试！", ""));

            string strRecordId = context.Request["modelid"];
            string[] idlist = strRecordId.Split(',');
            for (int i = 0; i < idlist.Length; i++)
            {
                Chenxin.Lib.Hr.Entity.WorkReport_InBox model = Chenxin.Lib.Hr.BLL.WorkReport_InBox.GetModel(new Guid(idlist[i]));
                model.isDeleted = false;
                model.isReaded = true;
                Chenxin.Lib.Hr.BLL.WorkReport_InBox.Update(model);
            }
            context.Response.Write(retExecResult(Constants.ExecResult.Succ, "恢复成功！", ""));
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    public void SetWorkReportIsRead(HttpContext context)
    {
        try
        {
            if (string.IsNullOrEmpty(context.Request["modelid"]))
                context.Response.Write(retExecResult(Constants.ExecResult.Error, "标识不存在，请重试！", ""));

            string strRecordId = context.Request["modelid"];

            Chenxin.Lib.Hr.Entity.WorkReport_InBox model = Chenxin.Lib.Hr.BLL.WorkReport_InBox.GetModel(new Guid(strRecordId));
            if (!model.isReaded)
            {
                model.isReaded = true;
                Chenxin.Lib.Hr.BLL.WorkReport_InBox.Update(model);
            }
            context.Response.Write(retExecResult(Constants.ExecResult.Succ, "" + model.WorkReportId + "", "{modelid:'" + model.WorkReportId + "'}"));

        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }
}